package com.hnas.ecard.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.hnas.common.util.CommonUtils;
import com.hnas.core.dao.PageBean;
import com.hnas.core.dto.DTOPagedList;
import com.hnas.core.util.DateUtil;
import com.hnas.core.util.MD5Util;
import com.hnas.core.util.StringUtil;
import com.hnas.ecard.dao.MerchantDao;
import com.hnas.ecard.mapper.MerchantMapper;
import com.hnas.ecard.orm.Merchant;
import com.hnas.ecard.service.MerchantService;
import com.hnas.ecard.service.dto.DTOMerchant;
import com.hnas.ecard.service.search.DTOMerchantSearch;

@Component("merchantService")
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public class MerchantServiceImpl implements MerchantService {

	@Autowired
	private MerchantDao merchantDao;

	String uploadFile = "/upload";

	@Value("#{component['uploadFileSize']}")
	private String uploadFileSize;

	@Override
	public DTOPagedList<DTOMerchant> search(DTOMerchantSearch con) {
		DTOPagedList<DTOMerchant> pageList = new DTOPagedList<DTOMerchant>();
		List<DTOMerchant> list = new ArrayList<DTOMerchant>();
		PageBean<Merchant> page = new PageBean<Merchant>();
		page.setPageNo(con.getPageNo());
		page.setPageSize(con.getPageSize());
		page.setTotalCount(con.getTotalCount());
		StringBuffer sb = new StringBuffer();
		List<Object> paras = new ArrayList<Object>();
		int j = 1;
		if (StringUtil.isNotEmpty(con.getName())) {
			sb.append(" and t.name like ?" + j++);
			paras.add("%" + con.getName().trim() + "%");
		}
		if (sb.length() > 0) {
			sb.delete(0, 5);
			sb.insert(0, " from Merchant t where ");
		} else {
			sb.append(" from Merchant t ");
		}
		sb.append(" order by t.updateTime desc");
		page.setQuery(sb.toString());
		page.setQueryCount("select count(t.id) " + sb);
		this.merchantDao.queryByPage(page, paras.toArray());
		pageList.setPageNo(page.getPageNo());
		pageList.setPageSize(page.getPageSize());
		pageList.setTotalCount(page.getTotalCount());
		for (Merchant vo : page.getList()) {
			DTOMerchant dto = new DTOMerchant();
			dto = MerchantMapper.getInstance().mapToValue(vo);
			list.add(dto);
		}
		pageList.setList(list);
		return pageList;
	}

	@Override
	public void deleteById(String id) {
		merchantDao.deleteById(id);
	}

	@Override
	public DTOMerchant findById(String id) {
		DTOMerchant dto = new DTOMerchant();
		Merchant vo = merchantDao.find(id);
		if (null != vo) {
			BeanUtils.copyProperties(vo, dto);
		} else {
			dto = null;
		}
		return dto;
	}

	@Override
	public Merchant saveOrUpdate(DTOMerchant dto, HttpServletRequest request) throws IOException {
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		String pic = "";
		Merchant vo = new Merchant();
		BeanUtils.copyProperties(dto, vo);
		if (multipartResolver.isMultipart(request)) {
			// 将request变成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 获取multiRequest 中所有的文件名
			MultipartFile file = multiRequest.getFile("merchant_pic");
			if (null != file&&file.getSize()>0) {
				String filePath = request.getServletContext().getRealPath("/") + "upload";
				pic = uploadFile+ writeFile(file, filePath);
				vo.setPic(pic);
			}
		}
		if (StringUtil.isEmpty(dto.getId())) {
			vo.setCreateTime(DateUtil.dateTimeToString(new Date()));
			vo.setUpdateTime(DateUtil.dateTimeToString(new Date()));
			vo.setId(CommonUtils.getUUID());
			vo.setIsDeleted(false);
			merchantDao.persist(vo);
		} else {
			vo.setUpdateTime(DateUtil.dateTimeToString(new Date()));
			merchantDao.merge(vo);
		}

		return vo;
	}

	public void uploadFile(HttpServletRequest request, String uploadFile) throws IOException {
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		if (multipartResolver.isMultipart(request)) {
			// 将request变成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 获取multiRequest 中所有的文件名
			MultipartFile file = multiRequest.getFile("merchant_pic");
			if (null != file) {
				writeFile(file, uploadFile);
			}

		}
	}

	public String writeFile(MultipartFile file, String uploadFile) throws IOException {
		InputStream in = null;
		FileOutputStream out = null;
		if (file != null) {
			Long fileSize = file.getSize();
			if (fileSize > 0 && fileSize < Long.parseLong(uploadFileSize)) {
				String path = "/";
				String fileRealName = file.getOriginalFilename();
				String md5Value = MD5Util.md5Hex(fileRealName.getBytes());
				String firstFour = md5Value.substring(0, 4);
				File firFile = new File(uploadFile, (path + firstFour));
				if (!firFile.exists() && !firFile.isDirectory()) {
					firFile.mkdirs();
				}
				String suffix = fileRealName.substring(fileRealName.lastIndexOf("."));
				String fileName = md5Value + fileRealName.substring(fileRealName.lastIndexOf("."));
				path = path + firstFour + "/" + fileName;
				File savePath = new File(uploadFile, path);
				if (!savePath.exists()) {// 当文件不存在时候才进行读写，否则跳出
					in = file.getInputStream();
					out = new FileOutputStream(savePath);
					byte[] b = new byte[1024];
					int len = -1;
					while ((len = in.read(b)) != -1) {
						out.write(b, 0, len);
					}
					out.flush();
				}
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
				return path;
			}
		}
		return null;
	}

}
